// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database();
const _ = db.command;
const $ = db.command.aggregate
// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const{page,limit,order}=event

  let sortcs={jf:-1,avg:1,firstcount:-1}
  if (order=='avg') sortcs={avg:1,jf:-1,firstcount:-1}
  if (order=='firstcount') sortcs={firstcount:-1,jf:-1,avg:1}

  let jh=db.collection('user').aggregate().match({
    history:_.exists(true)
  }).project({
    jonnerName:1,
    jf:1,
    image:'$userWxInfo.avatarUrl',
    gender:'$userWxInfo.gender',
    city:'$userWxInfo.city',
    gametimes:$.size('$history'),
    avg:$.divide([$.sum('$history'), $.size('$history')]),
    firstcount:$.size($.filter({
      input: '$history',
      as: 'item',
      cond: $.eq(['$$item', 1])
    }))
  })
  if(order=='avg'){jh=jh.match({
    gametimes:_.gte(10)
  })}
  let prophb=await jh.sort(sortcs).skip((page-1)*limit).limit(limit).end()
  
  return prophb.list

}